package Model.InboxMessages;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DBAccess.DBAccess;

@WebServlet("/AutoCompleteServlet")
public class AutoCompleteServlet extends HttpServlet {
	private int count;
	private List<String> name;
	private String data = "Aman, Albela, Ali, Ankit, Azam, Aryan,"
			+ "Bhumi, Bharat, Bhaskar, Bigul, Chaman, Chaturvedi, Chatrapati,"
			+ "Chitra, Deno, Digboi, Deepak, Doremon, Elepahant, Eagle, Erose,"
			+ "Funny, Fun, Fruit, Galgotia, Ghosle, Gautam, Grish, Honda, Hari,"
			+ "Harsh, Irfan, India, Indu, John, Johny, Jyotsna, Karunya, Kirti,"
			+ "Koshla, Lion, Laugh, Leg, Lotus, Mohan, Marshal, Maurisus, Monaco,"
			+ "Neil, Nelson, Nurul, Omang, Oman, Ozone, Orient, Pawan, Puri, Pushkar,"
			+ "Quraishi, Qutar, Quarter, Ravindra, Rajesh,"
			+ "Rohit, Roshan, Sunil, Surat, Sah, Saurya, Trilok, Tiwari, Top, Torch"
			+ "UK, USA, Uzbekistan, Vasant, Varun, Vipul, Vaidya, Wasim, Waquar,"
			+ "Xenon, X-Mas, Yemen, Yen, Yokohama, Zero, Zambia,Zimbabwe";

	public void init(ServletConfig config) {
		new DBAccess();
		Statement st=null;
		ResultSet rs=null;
		name = new ArrayList<String>();
    	try {
    		st = DBAccess.con.createStatement();
    		rs = st.executeQuery("SELECT name, userID FROM accountdb");
    		while (rs.next()){
    			name.add(rs.getString(1)+"|"+rs.getString(2));
            }
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	DBAccess.close(st, rs);
		
		count = name.size();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		System.out.println(name);
		System.out.println(count);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String nm = request.getParameter("q");

		List<String> name = getData(nm);

		Iterator<String> itr = name.iterator();
		while (itr.hasNext()) {
			String country = (String) itr.next();
			out.println(country);
		}

	}
	

	public List<String> getData(String nm) {
		String country = null;
		nm = nm.toLowerCase();
		List<String> equal = new ArrayList<String>();
		for (int i = 0; i < count; i++) {
			country = name.get(i).toLowerCase();
			if (country.startsWith(nm)) {
				equal.add(name.get(i));
			}
		}
		return equal;
	}
}